package com.atguigu.tingshu.common.login;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.SneakyThrows;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 定义切面类
 * 通知为环绕通知
 */
@Aspect
@Component
public class GuiGuLoginAspect {
    @Autowired
    private RedisTemplate redisTemplate;

    @Around("execution(* com.atguigu.tingshu.*.api.*.*(..)) && @annotation(guiguLogin)")
    public Object loginAspect(ProceedingJoinPoint joinPoint,GuiguLogin guiguLogin) throws Throwable {
        Object o = new Object();
        //请求上下文
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //强转
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)requestAttributes;
        //获取request
        HttpServletRequest request = servletRequestAttributes.getRequest();
        //获取token
        String token = request.getHeader("token");
        String tokenRedis = RedisConstant.USER_LOGIN_KEY_PREFIX + token;

        UserInfoVo userInfoVo = (UserInfoVo) redisTemplate.opsForValue().get(tokenRedis);
        if (guiguLogin.required()&&userInfoVo == null){
            //如果进入说明，拦截且没有登录
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }

        if (userInfoVo!=null){
            AuthContextHolder.setUserId(userInfoVo.getId());
        }
        o=joinPoint.proceed();
        AuthContextHolder.removeUserId();

        return o;
    }
}
